<template>
  <a-layout-header class="header">
    <a-menu
      v-model:selectedKeys="selectedKeys1"
      theme="dark"
      mode="horizontal"
      :style="{ lineHeight: '64px' }"
    >
      <a-menu-item style="color: white; font-size: 16px"
        >wiki知识库</a-menu-item
      >
      <a-menu-item key="/"> <router-link to="/">首页</router-link></a-menu-item>
      <a-menu-item key="/userManage">
        <router-link to="/userManage">用户管理</router-link>
      </a-menu-item>
      <a-menu-item key="/ebookManage">
        <router-link to="/ebookManage">电子书管理</router-link>
      </a-menu-item>
      <a-menu-item key="/cateManage">
        <router-link to="/cateManage">分类管理</router-link>
      </a-menu-item>
      <a-menu-item key="/about">
        <router-link to="/about">关于我们</router-link>
      </a-menu-item>
      <a-menu-item class="login">
        <el-popover placement="bottom" trigger="hover">
          <template #reference>{{ login_title }} </template>
          <el-button style="width: 100%" @click="logout" :disabled="disLogout"
            >退出</el-button
          >
        </el-popover>
      </a-menu-item>
    </a-menu>
  </a-layout-header>

  <div></div>
</template>

<script setup lang="ts">
import { watch, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { getToken, removeToken, getName } from "@/util/auth";
import { userLogout } from "@/api/user";
import { message } from "ant-design-vue";

//
let selectedKeys1 = reactive<string[]>([]);
//路由
let router = useRouter();

watch(
  () => router.currentRoute.value,
  (newValue: any, oldValue: any) => {
    if (
      newValue.fullPath != "/ebookManage" &&
      newValue.fullPath != "/cateManage" &&
      newValue.fullPath.substring(0, 4) != "/doc" &&
      newValue.fullPath != "/userManage" &&
      newValue.fullPath != "/about"
    ) {
      selectedKeys1[0] = "/";
    } else {
      selectedKeys1[0] = newValue.fullPath;
    }
  },
  {
    immediate: true,
  }
);

// ================== login
const disLogout = ref<boolean>(true);
const login_title = ref<string>("----");
const setUserInfo = () => {
  let token: any = getToken();
  let name: any = getName();
  if (token && name) {
    disLogout.value = false;
    login_title.value = name;
  }
  // 没登录再路由返回了
};
setUserInfo();

// ================== logout
const logout = () => {
  sessionStorage.removeItem("loginUser");
  let token: any = getToken();
  // 退出登录
  if (token) {
    userLogout(token)
      .then((res) => {
        if (res.data.code === 10001) {
          removeToken();
          message.success("退出成功");
          setTimeout(() => {
            router.push("/login");
          }, 600);
        } else {
          message.error(res.data.msg);
        }
      })
      .catch((err) => {
        message.error(err.message);
      });
  }
};
</script>

<style scope>
.ant-menu-dark.ant-menu-horizontal {
  position: relative;
}
.login {
  position: absolute !important;
  right: 0 !important;
}
</style>
